<template>
    <div>
      <!-- 卡片组件 -->
      <el-card shadow="hover">
  
        <!-- 查询表单 -->
        <el-form :model="searchForm" label-width="80px" style="margin-top: 20px; display: flex; margin-left: 20px;">
        <el-button type="primary" @click="dialogVisible = true">新增轮播图</el-button>
  
          <el-form-item label="轮播图ID">
            <el-input v-model="searchForm.id" style="width: 200px;" placeholder="请输入轮播图ID" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 新增轮播图对话框 -->
      <el-dialog v-model="dialogVisible" title="新增轮播图" width="50%">
        <el-form :model="addForm" label-width="120px">
          <el-form-item label="轮播图名称">
            <el-input v-model="addForm.banner_bt_title" />
          </el-form-item>
          <el-form-item label="轮播图 URL">
            <el-input v-model="addForm.banner_url" />
          </el-form-item>
          <el-form-item label="轮播图图片">
            <div class="upload-container">
              <el-upload
                class="upload-demo"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-success="(res) => handleUploadSuccess(res, 'banner_img')"
                :before-upload="beforeUpload"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">拖拽文件到此处或者 <em>点击上传</em></div>
                <div class="el-upload__tip">上传轮播图主图</div>
              </el-upload>
              <div class="image-preview" v-if="addForm.banner_img">
                <img :src="getFullImageUrl(addForm.banner_img)" alt="轮播图" class="preview-image" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="轮播图图标">
            <div class="upload-container">
              <el-upload
                class="upload-demo"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-success="(res) => handleUploadSuccess(res, 'banner_icon')"
                :before-upload="beforeUpload"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">拖拽文件到此处或者 <em>点击上传</em></div>
                <div class="el-upload__tip">上传轮播图图标</div>
              </el-upload>
              <div class="image-preview" v-if="addForm.banner_icon">
                <img :src="getFullImageUrl(addForm.banner_icon)" alt="图标" class="preview-image" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="addForm.banner_sort" :min="0" />
          </el-form-item>
          <el-form-item label="跳转类型">
            <el-input-number v-model.number="addForm.banner_jump_type" :min="0" />
          </el-form-item>
          <el-form-item label="轮播图类型">
            <el-input v-model.number="addForm.banner_type" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="addForm.status" placeholder="选择状态">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="标题">
            <el-input v-model="addForm.banner_title" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="addForm.banner_name" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 表格组件 -->
      <el-card shadow="hover" style="margin-top: 20px;">
        <el-table :data="bannerList" style="width: 100%" border>
          <el-table-column prop="ID" label="ID" width="80" />
          <el-table-column prop="banner_bt_title" label="标题" width="180" />
          <el-table-column prop="banner_img" label="轮播图片">
            <template #default="scope">
              <img
                :src="getFullImageUrl(scope.row.banner_img)"
                :alt="scope.row.banner_bt_title"
                style="width: 100px; height: 50px; object-fit: cover;"
              />
            </template>
          </el-table-column>
          <el-table-column prop="banner_icon" label="图标">
            <template #default="scope">
              <img
                v-if="scope.row.banner_icon"
                :src="getFullImageUrl(scope.row.banner_icon)"
                :alt="scope.row.banner_bt_title"
                style="width: 50px; height: 50px; object-fit: contain;"
              />
            </template>
          </el-table-column>
          <el-table-column prop="banner_url" label="链接" width="180" />
          <el-table-column prop="banner_sort" label="排序" width="100" />
          <el-table-column prop="banner_type" label="类型" width="100" />
          <el-table-column prop="CreatedAt" label="创建时间" width="200">
            <template #default="scope">
              {{ formatDate(scope.row.CreatedAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="UpdatedAt" label="更新时间" width="200">
            <template #default="scope">
              {{ formatDate(scope.row.UpdatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button style="margin-left: 11px; margin-bottom: 10px;"      type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
  
      <!-- 编辑轮播图对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑轮播图" width="50%">
        <el-form :model="editForm" label-width="120px">
          <el-form-item label="轮播图名称">
            <el-input v-model="editForm.banner_bt_title" />
          </el-form-item>
          <el-form-item label="轮播图 URL">
            <el-input v-model="editForm.banner_url" />
          </el-form-item>
          <el-form-item label="轮播图图片">
            <div class="upload-container">
              <el-upload
                class="upload-demo"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-success="(res) => handleEditUploadSuccess(res, 'banner_img')"
                :before-upload="beforeUpload"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">拖拽文件到此处或者 <em>点击上传</em></div>
                <div class="el-upload__tip">上传轮播图主图</div>
              </el-upload>
              <div class="image-preview" v-if="editForm.banner_img">
                <img :src="getFullImageUrl(editForm.banner_img)" alt="轮播图" class="preview-image" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="轮播图图标">
            <div class="upload-container">
              <el-upload
                class="upload-demo"
                drag
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-success="(res) => handleEditUploadSuccess(res, 'banner_icon')"
                :before-upload="beforeUpload"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">拖拽文件到此处或者 <em>点击上传</em></div>
                <div class="el-upload__tip">上传轮播图图标</div>
              </el-upload>
              <div class="image-preview" v-if="editForm.banner_icon">
                <img :src="getFullImageUrl(editForm.banner_icon)" alt="图标" class="preview-image" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="editForm.banner_sort" :min="0" />
          </el-form-item>
          <el-form-item label="跳转类型">
            <el-input-number v-model.number="editForm.banner_jump_type" :min="0" />
          </el-form-item>
          <el-form-item label="轮播图类型">
            <el-input v-model.number="editForm.banner_type" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="editForm.status" placeholder="选择状态">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="标题">
            <el-input v-model="editForm.banner_title" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="editForm.banner_name" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import axios from 'axios' // 引入 axios 用于接口请求
  import { ElMessage } from 'element-plus'
  
  // 定义轮播图数据接口
  interface Banner {
    ID: number
    banner_bt_title: string
    banner_img: string
    banner_url: string
    banner_sort: number
    banner_jump_type: number
    banner_type: string
    banner_icon: string
    status: number
    banner_title: string
    banner_name: string
    CreatedAt: string
    UpdatedAt: string
  }
  
  // 存储轮播图列表数据
  const bannerList = ref<Banner[]>([])
  
  // 从本地存储获取 token
  const token = localStorage.getItem('vue_admin_template_token')
  
  // 获取轮播图数据的函数
  const getBannerList = async () => {
    try {
      const res = await axios.get('http://211.154.24.179/api/banner/GetBanner', {
        headers: {
          Authorization: `${token}` // 在请求头中添加 token
        }
      })
      if (res.status === 200) {
        bannerList.value = res.data.data // 假设接口返回的数据直接是轮播图列表数组
      }
    } catch (error) {
      console.error('获取轮播图数据失败', error)
    }
  }
  
  // 格式化日期
  const formatDate = (dateString: string) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString()
  }
  
  // 页面加载时获取轮播图数据
  onMounted(async () => {
    await getBannerList()
    console.log(bannerList.value)
  })
  
  // 删除轮播图
  const handleDelete = async (banner: Banner) => {
    try {
      console.log(banner.ID)
      const res = await axios.delete(`http://211.154.24.179/api/banner/DeleteBannerID/${banner.ID}`, {
        headers: {
          Authorization: `${token}` // 在请求头中添加 token
        }
      })
      if (res.status === 200) {
        // 删除成功，更新列表数据
        bannerList.value = bannerList.value.filter((item) => item.ID !== banner.ID)
      }
    } catch (error) {
      console.error('删除轮播图失败', error)
    }
  }
  
  // 表单数据
  const searchForm = ref({
    id: ''
  })
  
  // 查询轮播图
  const handleSearch = async () => {
    try {
      if (!searchForm.value.id) {
        ElMessage.error('请输入轮播图ID')
        return
      }
      const res = await axios.get(`http://211.154.24.179/api/banner/GetBannerID/${searchForm.value.id}`, {
        headers: {
          Authorization: `${token}` // 在请求头中添加 token
        }
      })
      if (res.status === 200 && res.data.data) {
        bannerList.value = [res.data.data]
      } else {
        ElMessage.error('查询失败或没有找到对应的轮播图')
      }
    } catch (error) {
      console.error('查询轮播图失败', error)
      ElMessage.error('查询轮播图失败')
    }
  }
  
  // 新增轮播图对话框
  const dialogVisible = ref(false)
  
  // 新增轮播图表单数据
  const addForm = ref({
    banner_bt_title: '',
    banner_url: '',
    banner_img: '',
    banner_sort: 0,
    banner_jump_type: 0, // 默认值为 0
    banner_type: '',
    banner_icon: '',
    status: 0,
    banner_title: '',
    banner_name: ''
  })
  
  // 上传文件的接口地址
  const uploadUrl = 'http://211.154.24.179/api/qiniu/UploadFile'
  
  // 上传文件的请求头
  const uploadHeaders = ref({
    Authorization: `${token}`
  })
  
  // 服务器基础URL
  const BASE_URL = 'http://211.154.24.179'
  
  // 获取完整的图片URL
  const getFullImageUrl = (url: string) => {
    if (!url) return ''
    if (url.startsWith('http')) {
      return url
    }
    return `${BASE_URL}${url}`
  }
  
  // 文件上传成功后的回调
  const handleUploadSuccess = (response: any, field: 'banner_img' | 'banner_icon') => {
    if (response.success) {
      addForm.value[field] = response.data
      ElMessage.success('文件上传成功')
    } else {
      ElMessage.error('文件上传失败')
    }
  }
  
  // 文件上传前的钩子
  const beforeUpload = (file: any) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
      ElMessage.error('只能上传图片文件')
      return false
    }
    return true
  }
  
  // 处理新增轮播图
  const handleAdd = async () => {
    try {
      // 确保 banner_jump_type 是整数
      addForm.value.banner_jump_type = parseInt(addForm.value.banner_jump_type.toString())
      const res = await axios.post('http://211.154.24.179/api/banner/CreateBanner', addForm.value, {
        headers: {
          Authorization: `${token}` // 在请求头中添加 token
        }
      })
      if (res.status === 200) {
        // 添加成功，更新列表数据
        bannerList.value.push(res.data.data)
        dialogVisible.value = false
        addForm.value = {
          banner_bt_title: '',
          banner_url: '',
          banner_img: '',
          banner_sort: 0,
          banner_jump_type: 0,
          banner_type: '',
          banner_icon: '',
          status: 0,
          banner_title: '',
          banner_name: ''
        }
      }
    } catch (error) {
      console.error('新增轮播图失败', error)
    }
  }
  
  // 编辑轮播图对话框
  const editDialogVisible = ref(false)
  
  // 编辑轮播图表单数据
  const editForm = ref({
    ID: 0,
    banner_bt_title: '',
    banner_url: '',
    banner_img: '',
    banner_sort: 0,
    banner_jump_type: 0,
    banner_type: '',
    banner_icon: '',
    status: 0,
    banner_title: '',
    banner_name: ''
  })
  
  // 处理编辑按钮点击
  const handleEdit = (row: Banner) => {
    editForm.value = { ...row }
    editDialogVisible.value = true
  }
  
  // 处理编辑时的图片上传成功
  const handleEditUploadSuccess = (response: any, field: 'banner_img' | 'banner_icon') => {
    if (response.success) {
      editForm.value[field] = response.data
      ElMessage.success('文件上传成功')
    } else {
      ElMessage.error('文件上传失败')
    }
  }
  
  // 处理更新轮播图
  const handleUpdate = async () => {
    try {
      // 确保 banner_jump_type 是整数
      editForm.value.banner_jump_type = parseInt(editForm.value.banner_jump_type.toString())
      const res = await axios.put('http://211.154.24.179/api/banner/UpdateBanner', editForm.value, {
        headers: {
          Authorization: `${token}`
        }
      })
      if (res.status === 200) {
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        // 更新列表数据
        const index = bannerList.value.findIndex(item => item.ID === editForm.value.ID)
        if (index !== -1) {
          bannerList.value[index] = { ...editForm.value }
        }
      }
    } catch (error) {
      console.error('更新轮播图失败', error)
      ElMessage.error('更新轮播图失败')
    }
  }
  </script>
  
  <style scoped>
  .no-banner-tips {
    text-align: center;
    padding: 20px;
    color: #999;
  }
  
  .upload-container {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .image-preview {
    width: 200px;
    height: 100px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .preview-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }
  </style>